import React, { useEffect, useState, useCallback } from 'react';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { Card, Button, Descriptions, MessagePlugin, Row, Col, Loading } from 'tdesign-react';
import { ArrowLeftIcon } from 'tdesign-icons-react';
import { getDetailApi } from 'api/useManage/flowExpendStatistics';
import './index.module.less';
import SakuraSearchForm from 'components/SakuraSearchForm';
import IppeakTable from 'components/IppeakTable';
import { createColumns } from 'utils/tableUtils';
import { createRequestParams } from 'utils';
import { ALL_PROVIDER_MAP } from 'constants';

interface DetailData {
  id: string;
  user_id: string;
  username: string;
  email: string;
  flow_usage: number;
  created_at: string;
  updated_at: string;
  [key: string]: any;
}

// 初始查询参数
const INITIAL_QUERY = {
  page: 1,
  page_size: 10,
  username: '',
  uid:'',
  type:6
};

// 初始表格状态
const INITIAL_TABLE_STATE = {
  list: [],
  total: 0,
  current: 1,
  pageSize: 10,
};

const FlowExpendDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const location = useLocation();

  const username = location.state?.username || '';
  const date = location.state?.date || '';

  const [loading, setLoading] = useState(false);
  const [tableLoading, setTableLoading] = useState(false);
  const [detailData, setDetailData] = useState<any | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([]);
  const [table, setTable] = useState(INITIAL_TABLE_STATE);
  const [query, setQuery] = useState({
    ...INITIAL_QUERY,
    username, // 使用传递的username初始化
    date,
  });
  const { list, total } = table;

  // 获取详情数据的API
  const fetchDetailData = async (recordId: string) => {
    try {
      const res: any = await getDetailApi({ id: recordId });
      setDetailData(res);
    } catch (error) {
      MessagePlugin.error('获取详情失败');
    }
  };

  const fetchTableList = useCallback(
    async (page?: number, pageSize?: number) => {
      setTableLoading(true);
      try {
        const requestParams = createRequestParams({
          uid: id,
          username: query.username, // 添加username参数
          date: query.date,
          type:6,
          page: page || query.page,
          page_size: pageSize || query.page_size,
        });
        const res: any = await getDetailApi(requestParams);
        setTable((pre: any) => ({
          ...pre,
          list: res.results || res.data || [],
          total: res.total || 0,
        }));
      } catch (err) {
        console.error('获取表格数据失败:', err);
      } finally {
        setTableLoading(false);
      }
    },
    [id, query.username],
  );

  const columns = createColumns([
    {
      label: '连接时间',
      key: 'connect',
      width: '150',
      type: 'date',
    },
    {
      label: '释放时间',
      key: 'release',
      type: 'date',
      width: 160,
    },
    {
      label: '目标网站',
      key: 'target_addr',
      width: 250,
    },
    {
      label: '连接状态',
      key: 'req_success',
      render: ({ row }: any) => <div>{row.req_success ? '成功' : '失败'}</div>,

    },
    {
      label: '连接协议',
      key: 'protocol',
    },
    {
      label: '端口',
      key: 'in_local_addr',
    },
    {
      label: '上行流量',
      key: 'up_bytes',
    },
    {
      label: '下行流量',
      key: 'down_bytes',
    },
    {
      label: '消耗流量',
      key: 'traff_count',
    },
    {
      label: '资源商',
      key: 'provider',
      width: 140,
      enumConf: {
        options: ALL_PROVIDER_MAP,
      },
    },
  ]);

  const formFields: any[] = [
    {
      label: '用户ID',
      name: 'uid',
      type: 'input',
      disabled: true,
      initialValue: id,
    },
    {
      label: '邮箱',
      name: 'username',
      type: 'input',
      disabled: true,
      initialValue: username || '', 
      colWrap: {
        colSpan: 2.5,
        labelWidth: 50,
      },
    },
  ];

  const onSelectChange = useCallback((value: (string | number)[]) => {
    setSelectedRowKeys(value);
  }, []);

  const handleSearch = useCallback((values: any) => {
    setQuery((pre) => ({
      ...pre,
      ...values,
      page: 1,
    }));
  }, []);

  // 处理重置
  const handleReset = useCallback(() => {
    setQuery(INITIAL_QUERY);
  }, []);

  const handlePaginationChange = useCallback((page: number, pageSize: number) => {
    setQuery((pre) => ({
      ...pre,
      page,
      page_size: pageSize,
    }));
  }, []);

  // 处理当前页变化
  const handleCurrentChange = useCallback(
    (current: number, pageInfo: any) => {
      handlePaginationChange(current, query.page_size);
    },
    [query.page_size, handlePaginationChange],
  );

  // 处理每页条数变化
  const handlePageSizeChange = useCallback(
    (size: number) => {
      handlePaginationChange(1, size); // 切换每页条数时重置到第一页
    },
    [handlePaginationChange],
  );

  useEffect(() => {
    if (id) {
      fetchTableList(query.page, query.page_size);
    }
  }, [id, query.page, query.page_size, query.username, fetchTableList]);

  const handleBack = () => {
    navigate(-1);
  };

  return (
    <div className='flow-expend-detail'>
      <Card>
        <div >
        <Row align='top'>
          <Col style={{marginRight: '16px'}}>
            <Button theme='default' variant='text' icon={<ArrowLeftIcon />} onClick={handleBack}>返回列表</Button>
          </Col>
          <Col>
            <SakuraSearchForm fields={formFields} onSearch={handleSearch} onReset={handleReset} hideButtons={true} rowStyle={{ marginBottom: '0' }} gutterStyle={[16,0]} />
          </Col>
        </Row>
        </div>
        <IppeakTable
          loading={tableLoading}
          dataSource={list}
          columns={columns}
          tableHeight={268}
          rowKey='id'
          selectedRowKeys={selectedRowKeys}
          onSelectChange={onSelectChange}
          pagination={{
            pageSize: query.page_size,
            total,
            current: query.page,
            showJumper: true,
            onCurrentChange: handleCurrentChange,
            onPageSizeChange: handlePageSizeChange,
          }}
        />
      </Card>
    </div>
  );
};

export default FlowExpendDetail;
